package cn.hh.wechatkit.api.message;

import cn.hh.wechatkit.data.postdata.card.Meta_CardCheckTicketStatePostData;
import cn.hh.wechatkit.data.postdata.message.meta_SendTemplateMsgData;
import cn.hh.wechatkit.data.returndata.Meta_RMsg_Base;
import cn.hh.wechatkit.data.returndata.card.Meta_RData_CardState;
import cn.hh.wechatkit.exception.Wx_Exception_BadNetwork;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidJsonParse;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidResponse;
import cn.hhchat.kit.http.httpUtil;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;

import java.io.IOException;

import static cn.hh.wechatkit.helper.WxConst.SendTemplateMsg_POST_URL;

/**
 * Created this one by HMH on 2018/10/1.
 */
@Slf4j
@Data
public class WxAppAPI_Message_SendTemplate_API {
    /**
     * 微信卡券状态查询 API
     * @param msgData
     * @param ACCESS_TOKEN 基础Token
     * @return 卡券状态消息
     */
    public static Meta_RMsg_Base sendTemplateMsg(meta_SendTemplateMsgData msgData, String ACCESS_TOKEN)  {
        String url = SendTemplateMsg_POST_URL.replace("ACCESS_TOKEN", ACCESS_TOKEN);
        Response response;
        log.info(msgData.toString());
        try {
            log.info("send template msg: body={}", JSON.toJSONString(msgData));
            response = httpUtil.postJson(url, msgData);
        } catch (IOException e) {
            log.error(" ==> 网络请求失败", e);
            throw new Wx_Exception_BadNetwork("网络请求失败", e);
        }
        //获取数据
        if (response != null) {
            String body;
            try {
                body = response.body().string();
                return JSON.parseObject(body, Meta_RMsg_Base.class);
            } catch (IOException e) {
                log.error(" ==> json转换失败", e);
                throw new Wx_Exception_InvalidJsonParse("json转换失败");
            }
        }
        throw new Wx_Exception_InvalidResponse("没有收到响应，或者请求出错");
    }
}
